package com.wjx.article_sys.service.impl;

import com.wjx.article_sys.dao.CommentMapper;
import com.wjx.article_sys.entity.Comment;
import com.wjx.article_sys.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    public CommentMapper commentMapper;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private HttpSession session;
    @Override
    public List<Comment> queryCommentByArticleId(Integer id){
        return commentMapper.queryCommentByArticleId(id);
    }
    @Override
    public void addComment(String content,Integer aId)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String author =  session.getAttribute("userName").toString();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String postTime = simpleDateFormat.format(new Date(System.currentTimeMillis()));
        try {
            commentMapper.addComment(content,author,postTime,aId);
            response.getWriter().write("<script>alert('评论发表成功');</script>");
        }catch (Exception e){
            e.printStackTrace();
            response.getWriter().write("<script>alert('评论发表失败');</script>");
        }
    }

    @Override
    public void updateCommentById(Integer id,String content) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try{
            commentMapper.updateCommentById(id,content);
            response.getWriter().write("<script>alert('评论修改成功');</script>");
        }catch (Exception e){
            e.printStackTrace();
            response.getWriter().write("<script>alert('评论修改失败');</script>");
        }
    }

    @Override
    public void deleteCommentById(Integer id) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try{
            commentMapper.deleteCommentById(id);
            response.getWriter().write("<script>alert('评论删除成功');</script>");
        }catch (Exception e){
            e.printStackTrace();
            response.getWriter().write("<script>alert('评论删除失败');</script>");
        }
    }
}
